// 全局变量
let currentParameter = 'temperature';
let currentChartType = 'line';
let chartInstance = null;
let updateInterval = null;

// 注册监测页面处理程序
pageManager.registerPage('monitor', {
    // 保存页面状态
    currentParameter: 'temperature',
    currentChartType: 'line',
    chartInstance: null,
    updateInterval: null,

    init() {
        // 初始化时先设置默认参数
        const defaultParam = document.querySelector('.parameter-item[data-param="temperature"]');
        if (defaultParam) {
            defaultParam.classList.add('active');
        }

        // 初始化事件监听
        this.initEventListeners();
        
        // 使用 requestAnimationFrame 确保DOM已完全渲染
        requestAnimationFrame(() => {
            const chartContainer = document.getElementById('mainChart');
            if (chartContainer) {
                this.chartInstance = echarts.init(chartContainer);
                this.updateChart();
                
                // 创建 ResizeObserver 监听容器尺寸变化
                this.resizeObserver = new ResizeObserver(() => {
                    if (this.chartInstance) {
                        this.chartInstance.resize();
                    }
                });
                
                this.resizeObserver.observe(chartContainer);
            }
        });
    },

    cleanup() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
        if (this.chartInstance) {
            this.chartInstance.dispose();
            this.chartInstance = null;
        }
        
        // 清理 ResizeObserver
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
    },

    // 初始化图表
    initChart() {
        const chartContainer = document.getElementById('monitorChart');
        if (!chartContainer) {
            console.error('找不到图表容器');
            return;
        }

        // 如果已存在实例，先销毁
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }

        // 创建新实例
        this.chartInstance = echarts.init(chartContainer);
        
        // 设置图表响应式
        window.addEventListener('resize', () => {
            this.chartInstance && this.chartInstance.resize();
        });

        // 首次更新图表
        this.updateChart();
    },

    // 初始化事件监听
    initEventListeners() {
        // 参数切换
        document.querySelectorAll('.parameter-item').forEach(item => {
            item.addEventListener('click', () => {
                document.querySelectorAll('.parameter-item').forEach(p => {
                    p.classList.remove('active');
                });
                item.classList.add('active');
                this.currentParameter = item.dataset.param;
                this.updateData();
            });
        });

        // 时间范围切换
        const timeRange = document.getElementById('timeRange');
        if (timeRange) {
            timeRange.addEventListener('change', () => {
                this.updateData();
            });
        }

        // 图表类型切换
        const chartType = document.getElementById('chartType');
        if (chartType) {
            chartType.addEventListener('change', (e) => {
                this.currentChartType = e.target.value;
                this.updateChart();
            });
        }

        // 刷新间隔切换
        const refreshInterval = document.getElementById('refreshInterval');
        if (refreshInterval) {
            refreshInterval.addEventListener('change', () => {
                this.startAutoUpdate();
            });
        }
    },

    // 生成模拟数据
    generateData(hours) {
        const now = new Date();
        const data = [];
        for (let i = hours; i >= 0; i--) {
            const time = new Date(now - i * 3600000);
            let value;
            switch (this.currentParameter) {
                case 'temperature':
                    value = 20 + Math.random() * 10;
                    break;
                case 'humidity':
                    value = 50 + Math.random() * 30;
                    break;
                case 'light':
                    value = 50000 + Math.random() * 50000;
                    break;
                case 'soil':
                    value = 30 + Math.random() * 30;
                    break;
            }
            data.push({
                time: time.toLocaleTimeString(),
                value: value.toFixed(1)
            });
        }
        return data;
    },

    // 更新图表
    updateChart() {
        if (!this.chartInstance) return;
        
        // 在设置option之前，确保容器可见
        this.chartInstance.resize();
        
        const timeRange = parseInt(document.getElementById('timeRange').value);
        const data = this.generateData(timeRange);
        
        const option = {
            title: {
                text: this.getParameterTitle(),
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params) => {
                    const data = params[0];
                    return `${data.name}<br/>${data.value}${this.getParameterUnit()}`;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.map(item => item.time)
            },
            yAxis: {
                type: 'value',
                name: this.getParameterUnit(),
                axisLabel: {
                    formatter: `{value}${this.getParameterUnit()}`
                }
            },
            series: [{
                name: this.getParameterTitle(),
                type: this.currentChartType,
                data: data.map(item => item.value),
                smooth: true,
                areaStyle: this.currentChartType === 'line' ? {
                    opacity: 0.1
                } : undefined,
                itemStyle: {
                    color: this.getParameterColor()
                },
                lineStyle: {
                    width: 2
                }
            }]
        };

        this.chartInstance.setOption(option);
    },

    // 获取参数对应的颜色
    getParameterColor() {
        const colors = {
            temperature: '#ff6b6b',
            humidity: '#4dabf7',
            light: '#ffd43b',
            soil: '#69db7c'
        };
        return colors[this.currentParameter] || '#5c7cfa';
    },

    // 更新数据概览
    updateOverview() {
        const data = this.generateData(24);
        const values = data.map(item => parseFloat(item.value));
        
        document.getElementById('overview-current').textContent = values[values.length - 1] + this.getParameterUnit();
        document.getElementById('overview-max').textContent = Math.max(...values).toFixed(1) + this.getParameterUnit();
        document.getElementById('overview-min').textContent = Math.min(...values).toFixed(1) + this.getParameterUnit();
        document.getElementById('overview-avg').textContent = (values.reduce((a, b) => a + b) / values.length).toFixed(1) + this.getParameterUnit();
    },

    // 更新数据表格
    updateDataTable() {
        const data = this.generateData(10);
        const tbody = document.getElementById('dataTableBody');
        tbody.innerHTML = data.map(item => {
            const trend = Math.random() > 0.5 ? 'up' : 'down';
            const trendIcon = trend === 'up' ? '↑' : '↓';
            const trendClass = trend === 'up' ? 'trend-up' : 'trend-down';
            return `
                <tr>
                    <td>${item.time}</td>
                    <td>${item.value}${this.getParameterUnit()}</td>
                    <td>${this.getParameterStatus(parseFloat(item.value))}</td>
                    <td class="${trendClass}">${trendIcon}</td>
                </tr>
            `;
        }).join('');
    },

    // 获取参数标题
    getParameterTitle() {
        const titles = {
            temperature: '温度监测',
            humidity: '湿度监测',
            light: '光照监测',
            soil: '土壤湿度监测'
        };
        return titles[this.currentParameter];
    },

    // 获取参数单位
    getParameterUnit() {
        const units = {
            temperature: '°C',
            humidity: '%',
            light: ' lux',
            soil: '%'
        };
        return units[this.currentParameter];
    },

    // 获取参数状态
    getParameterStatus(value) {
        switch (this.currentParameter) {
            case 'temperature':
                if (value < 15) return '偏低';
                if (value > 30) return '偏高';
                return '正常';
            case 'humidity':
                if (value < 40) return '干燥';
                if (value > 80) return '潮湿';
                return '适宜';
            case 'light':
                if (value < 30000) return '光照不足';
                if (value > 90000) return '光照强';
                return '适中';
            case 'soil':
                if (value < 35) return '偏干';
                if (value > 70) return '偏湿';
                return '适宜';
        }
    },

    // 启动自动更新
    startAutoUpdate() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
        const interval = parseInt(document.getElementById('refreshInterval').value) * 1000;
        this.updateInterval = setInterval(() => this.updateData(), interval);
    },

    // 更新所有数据
    updateData() {
        this.updateChart();
        this.updateOverview();
        this.updateDataTable();
    }
});

// 初始化函数
function initMonitor() {
    initChart();
    initEventListeners();
    updateData();
    startAutoUpdate();
}

// 初始化图表
function initChart() {
    chartInstance = echarts.init(document.getElementById('mainChart'));
    updateChart();
}

// 初始化事件监听
function initEventListeners() {
    // 参数切换
    document.querySelectorAll('.parameter-item').forEach(item => {
        item.addEventListener('click', () => {
            document.querySelector('.parameter-item.active').classList.remove('active');
            item.classList.add('active');
            currentParameter = item.dataset.param;
            updateChart();
            updateOverview();
        });
    });

    // 图表类型切换
    document.querySelectorAll('.btn-chart-type').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelector('.btn-chart-type.active').classList.remove('active');
            btn.classList.add('active');
            currentChartType = btn.dataset.type;
            updateChart();
        });
    });

    // 时间范围切换
    document.getElementById('timeRange').addEventListener('change', (e) => {
        updateChart();
    });

    // 刷新间隔切换
    document.getElementById('refreshInterval').addEventListener('change', (e) => {
        startAutoUpdate();
    });
}

// 生成模拟数据
function generateData(hours) {
    const now = new Date();
    const data = [];
    for (let i = hours; i >= 0; i--) {
        const time = new Date(now - i * 3600000);
        let value;
        switch (currentParameter) {
            case 'temperature':
                value = 20 + Math.random() * 10;
                break;
            case 'humidity':
                value = 50 + Math.random() * 30;
                break;
            case 'light':
                value = 50000 + Math.random() * 50000;
                break;
            case 'soil':
                value = 30 + Math.random() * 30;
                break;
        }
        data.push({
            time: time.toLocaleTimeString(),
            value: value.toFixed(1)
        });
    }
    return data;
}

// 更新图表
function updateChart() {
    const timeRange = parseInt(document.getElementById('timeRange').value);
    const data = generateData(timeRange);
    
    const option = {
        title: {
            text: getParameterTitle(),
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.time)
        },
        yAxis: {
            type: 'value',
            name: getParameterUnit()
        },
        series: [{
            data: data.map(item => item.value),
            type: currentChartType,
            smooth: true,
            areaStyle: currentChartType === 'line' ? {
                opacity: 0.1
            } : undefined
        }]
    };

    chartInstance.setOption(option);
}

// 更新数据概览
function updateOverview() {
    const data = generateData(24);
    const values = data.map(item => parseFloat(item.value));
    
    document.getElementById('overview-current').textContent = values[values.length - 1] + getParameterUnit();
    document.getElementById('overview-max').textContent = Math.max(...values).toFixed(1) + getParameterUnit();
    document.getElementById('overview-min').textContent = Math.min(...values).toFixed(1) + getParameterUnit();
    document.getElementById('overview-avg').textContent = (values.reduce((a, b) => a + b) / values.length).toFixed(1) + getParameterUnit();
}

// 更新数据表格
function updateDataTable() {
    const data = generateData(10);
    const tbody = document.getElementById('dataTableBody');
    tbody.innerHTML = data.map(item => {
        const trend = Math.random() > 0.5 ? 'up' : 'down';
        const trendIcon = trend === 'up' ? '↑' : '↓';
        const trendClass = trend === 'up' ? 'trend-up' : 'trend-down';
        return `
            <tr>
                <td>${item.time}</td>
                <td>${item.value}${getParameterUnit()}</td>
                <td>${getParameterStatus(parseFloat(item.value))}</td>
                <td class="${trendClass}">${trendIcon}</td>
            </tr>
        `;
    }).join('');
}

// 获取参数标题
function getParameterTitle() {
    const titles = {
        temperature: '温度监测',
        humidity: '湿度监测',
        light: '光照监测',
        soil: '土壤湿度监测'
    };
    return titles[currentParameter];
}

// 获取参数单位
function getParameterUnit() {
    const units = {
        temperature: '°C',
        humidity: '%',
        light: ' lux',
        soil: '%'
    };
    return units[currentParameter];
}

// 获取参数状态
function getParameterStatus(value) {
    switch (currentParameter) {
        case 'temperature':
            if (value < 15) return '偏低';
            if (value > 30) return '偏高';
            return '正常';
        case 'humidity':
            if (value < 40) return '干燥';
            if (value > 80) return '潮湿';
            return '适宜';
        case 'light':
            if (value < 30000) return '光照不足';
            if (value > 90000) return '光照强';
            return '适中';
        case 'soil':
            if (value < 35) return '偏干';
            if (value > 70) return '偏湿';
            return '适宜';
    }
}

// 更新所有数据
function updateData() {
    updateChart();
    updateOverview();
    updateDataTable();
}

// 启动自动更新
function startAutoUpdate() {
    if (updateInterval) {
        clearInterval(updateInterval);
    }
    const interval = parseInt(document.getElementById('refreshInterval').value) * 1000;
    updateInterval = setInterval(updateData, interval);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initMonitor);

// 窗口大小改变时重绘图表
window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize();
});

// 清理函数
function cleanup() {
    if (updateInterval) {
        clearInterval(updateInterval);
    }
    if (chartInstance) {
        chartInstance.dispose();
    }
}

// 页面卸载时清理资源
window.addEventListener('beforeunload', cleanup); 